<?php

namespace app\common\cachemodel\name_analyze;

use app\common\model\BaseCache;

class Zl9NameAnalyzeRecodeCreateNameRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl9_name_analyze_recode_create_name_record';

    /**
     * 获取 档案 起名 名字信息
     * @param int $rid
     * @return array|null
     */
    public function getRecodeCreateNameData(int $rid)
    {
        try
        {
            $data = $this->where(['rid' => $rid])->find();
            if ($data)
            {
                $data = $data->toArray();
                $data['create_names'] = isset($data['create_names']) && $data['create_names'] ? json_decode($data['create_names'], true) : [];
            }
            return $data;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return null;
        }
    }

    /**
     * 保存数据
     * @param int $uid
     * @param int $rid
     * @param array $names
     * @return void
     */
    public function SaveData(int $uid, int $rid, array $names)
    {
        $data = $this->getRecodeCreateNameData($rid);
        $nowTime = time();
        if ($data)
        {
            $nameList = array_merge($data['create_names'], $names);
            $nameList = array_values(array_unique($nameList));
            $this->where(['rid' => $rid])->update(['create_names' => json_encode($nameList, JSON_UNESCAPED_UNICODE), 'update_time' => $nowTime]);
        } else
        {
            $this->insert([
                'uid' => $uid,
                'rid' => $rid,
                'create_names' => json_encode($names, JSON_UNESCAPED_UNICODE),
                'create_time' => $nowTime,
                'update_time' => $nowTime,
            ]);
        }
    }
}